package com.elf.zero.form;

import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import androidx.appcompat.app.AlertDialog;

import com.elf.zero.datetime.DatetimePicker;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class FormDateTime extends FormTextView {

    private static String pattern = "yyyy-MM-dd HH:mm";
    private SimpleDateFormat dateTimeFormat;

    public FormDateTime(Context context) {
        super(context);
    }

    public FormDateTime(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void initView(AttributeSet attrs) {
        super.initView(attrs);

        dateTimeFormat = new SimpleDateFormat(pattern, Locale.getDefault());
        Date nowDate = Calendar.getInstance().getTime();
        setValue(dateTimeFormat.format(nowDate));

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
    }

    private void showDialog() {
        Calendar calendar = Calendar.getInstance();

        if (!TextUtils.isEmpty(getValue())) {
            try {
                calendar.setTime(dateTimeFormat.parse(getValue()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        final DatetimePicker dateTimePicker = new DatetimePicker(getContext());
        dateTimePicker.setDateTime(calendar);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("选择日期时间");
        builder.setView(dateTimePicker);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setValue(dateTimePicker.getDataTime(pattern));
            }
        });
        builder.setNeutralButton("取消", null);
        builder.show();
    }
}
